package com.xc.content.service.jobhandler;

import com.xc.base.exception.XcPlusException;
import com.xc.content.feignclient.SearchServiceClient;
import com.xc.content.mapper.CoursePublishMapper;
import com.xc.content.model.po.CoursePublish;
import com.xc.content.po.CourseIndex;
import com.xc.content.service.CoursePublishService;
import com.xc.messagesdk.model.po.MqMessage;
import com.xc.messagesdk.service.MessageProcessAbstract;
import com.xc.messagesdk.service.MqMessageService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * description 课程发布的任务类
 */
@Slf4j
@Component
public class CoursePublishTask extends MessageProcessAbstract {

    @Autowired
    private CoursePublishService coursePublishService;

    @Autowired
    private SearchServiceClient searchServiceClient;

    @Autowired
    private CoursePublishMapper coursePublishMapper;

    // 任务调度入口
    @XxlJob("CoursePublishJobHandler")
    public void coursePublishJobHandler() throws Exception {

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex(); // 执行器的序号，从0开始
        int shardTotal = XxlJobHelper.getShardTotal(); // 执行器总数
        // 调用抽象类的方法执行任务
        process(shardIndex, shardTotal, "course_publish", 10, 60);
    }

    // 课程发布任务处理
    @Override
    public boolean execute(MqMessage mqMessage) {
        // 获取消息相关的业务信息
        String businessKey1 = mqMessage.getBusinessKey1();
        long courseId = Integer.parseInt(businessKey1);

        // 课程静态化上传到minio
        generateCourseHtml(mqMessage, courseId);

        // 向elasticsearch写索引数据
        saveCourseIndex(mqMessage, courseId);

        // 向redis写缓存
        saveCourseCache(mqMessage, courseId);

        // 返回true表示任务完成
        return true;
    }

    // 生成课程静态化页面并上传至文件系统
    public void generateCourseHtml(MqMessage mqMessage, long courseId) {

        log.debug("开始进行课程静态化,课程id:{}", courseId);
        // 消息id
        Long taskId = mqMessage.getId();
        // 消息处理的service
        MqMessageService mqMessageService = this.getMqMessageService();
        // 消息幂等性处理 查询数据库取出该阶段执行状态
        int stageOne = mqMessageService.getStageOne(taskId);
        if (stageOne > 0) {
            log.debug("课程静态化已处理直接返回，课程id:{}", courseId);
            return;
        }

        // 开始进行课程静态化 生成html页面
        File file = coursePublishService.generateCourseHtml(courseId);
        if (file == null) {
            XcPlusException.cast("生成的静态页面为空");
        }
        // 将html上传到minio
        coursePublishService.uploadCourseHtml(courseId, file);

        // 第一阶段任务处理完成写任务状态为完成
        mqMessageService.completedStageOne(taskId);
    }

    // 将课程信息缓存至redis
    public void saveCourseCache(MqMessage mqMessage, long courseId) {
        log.debug("将课程信息缓存至redis,课程id:{}", courseId);
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    // 保存课程索引信息 第二个阶段任务
    public void saveCourseIndex(MqMessage mqMessage, long courseId) {
        // 任务id
        Long taskId = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
        // 取出第二个阶段状态
        int stageTwo = mqMessageService.getStageTwo(taskId);

        // 任务幂等性处理
        if (stageTwo > 0) {
            log.debug("课程索引信息已写入，无需执行...");
            return;
        }
        // 查询课程信息，调用搜索服务添加索引接口
        // 从课程发布表查询课程信息
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);

        CourseIndex courseIndex = new CourseIndex();
        BeanUtils.copyProperties(coursePublish, courseIndex);
        // 远程调用
        Boolean addCourseIndex = searchServiceClient.addCourseIndex(courseIndex);
        if (!addCourseIndex) {
            XcPlusException.cast("远程调用搜索服务添加课程索引失败");
        }

        //完成本阶段的任务
        mqMessageService.completedStageTwo(taskId);
    }
}
